// 1. 引入依赖项
import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
// 2. 注册组件
Vue.use(VueRouter)
// 3. 配置路由项

// 重写路由的push与replace方法
const originPush = VueRouter.prototype.push
const originreplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, okCallBack, errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    // 统一处理错误提示
    originPush.call(this, location).catch(() => {})
  } else {
    originPush.call(this, location, okCallBack, errCallBack)
  }
}

VueRouter.prototype.replace = function (location, okCallBack, errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    // 统一处理错误提示
    originreplace.call(this, location).catch(() => {})
  } else {
    originreplace.call(this, location, okCallBack, errCallBack)
  }
}

const router = new VueRouter({
  mode: 'history',
  routes,
  // 处理跳转到新页面时的滚动行为
  scrollBehavior(to, from, savedPosition) {
    // to表示到达的路由目标对象
    // from 表示来自于哪个路由对象
    // console.log(to,from)
    // console.log(savedPosition) // 记录上一个页面的位置 可以通过回退按钮来呈现
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})
//设置一个路由白名单,在白名单内的名字不会被拦截
const whiteList = ['home', 'login', 'register', 'search', 'detail', 'addCartSuccess', 'shopCart']
router.beforeEach((to, from, next) => {
  console.log('luyou', to, from, next)
  if (whiteList.includes(to.name) || store.state.user.userInfo.token) {
    next() //符合条件放行
    return
  }
  //跳转到登录页面
  next({
    name: 'login',
    query: {
      redirect: to.path //在地址栏拼接一下,表示之前访问的页面
    }
  })
})

// 4. 导出路由对象
export default router
